const hre = require("hardhat");

/**
 * 合约交互示例脚本
 * 演示如何使用 DigitalCollectionNFT 合约的各种功能
 */
async function main() {
  console.log("🚀 开始与 DigitalCollectionNFT 合约交互...\n");

  // 读取部署信息
  const fs = require("fs");
  const deploymentPath = `./deployments/${hre.network.name}.json`;
  
  if (!fs.existsSync(deploymentPath)) {
    console.error("❌ 未找到部署信息，请先运行部署脚本");
    console.log("运行: npm run deploy");
    return;
  }

  const deployment = JSON.parse(fs.readFileSync(deploymentPath, "utf8"));
  const contractAddress = deployment.contractAddress;

  console.log("📍 合约地址:", contractAddress);
  console.log("🌐 网络:", hre.network.name);
  console.log("");

  // 获取签名者
  const [owner, user1, user2] = await hre.ethers.getSigners();
  console.log("👤 Owner:", owner.address);
  console.log("👤 User1:", user1.address);
  console.log("👤 User2:", user2.address);
  console.log("");

  // 连接到已部署的合约
  const DigitalCollectionNFT = await hre.ethers.getContractFactory("DigitalCollectionNFT");
  const nft = DigitalCollectionNFT.attach(contractAddress);

  try {
    // ========== 1. 铸造NFT ==========
    console.log("📝 步骤 1: 铸造NFT");
    console.log("-".repeat(50));
    
    const mintTx = await nft.connect(owner).mint(
      owner.address,
      "ipfs://QmExampleHash123/metadata.json",
      1000  // 10% 版税
    );
    await mintTx.wait();
    console.log("✅ NFT #0 铸造成功");
    console.log("   - 所有者:", owner.address);
    console.log("   - 版税: 10%");
    console.log("");

    // ========== 2. 查询NFT信息 ==========
    console.log("🔍 步骤 2: 查询NFT信息");
    console.log("-".repeat(50));
    
    const tokenURI = await nft.tokenURI(0);
    const tokenOwner = await nft.ownerOf(0);
    const creator = await nft.creators(0);
    const royalty = await nft.royaltyPercent(0);
    
    console.log("   Token ID: 0");
    console.log("   URI:", tokenURI);
    console.log("   所有者:", tokenOwner);
    console.log("   创作者:", creator);
    console.log("   版税:", Number(royalty) / 100, "%");
    console.log("");

    // ========== 3. 挂单销售 ==========
    console.log("💰 步骤 3: 挂单销售NFT");
    console.log("-".repeat(50));
    
    const price = hre.ethers.parseEther("0.1");
    const listTx = await nft.connect(owner).listNFT(0, price);
    await listTx.wait();
    
    console.log("✅ NFT #0 已挂单");
    console.log("   - 价格:", hre.ethers.formatEther(price), "ETH");
    
    const listing = await nft.listings(0);
    console.log("   - 卖家:", listing.seller);
    console.log("   - 状态:", listing.isActive ? "在售" : "未在售");
    console.log("");

    // ========== 4. 查询在售NFT ==========
    console.log("🛒 步骤 4: 查询所有在售NFT");
    console.log("-".repeat(50));
    
    const activeListings = await nft.getActiveListings();
    console.log("   在售NFT数量:", activeListings.length);
    console.log("   Token IDs:", activeListings.toString());
    console.log("");

    // ========== 5. 购买NFT ==========
    console.log("🎁 步骤 5: User1 购买NFT");
    console.log("-".repeat(50));
    
    const buyTx = await nft.connect(user1).buyNFT(0, { value: price });
    await buyTx.wait();
    
    console.log("✅ NFT #0 购买成功");
    const newOwner = await nft.ownerOf(0);
    console.log("   - 新所有者:", newOwner);
    console.log("   - 支付金额:", hre.ethers.formatEther(price), "ETH");
    
    const listingAfterBuy = await nft.listings(0);
    console.log("   - 挂单状态:", listingAfterBuy.isActive ? "在售" : "已售出");
    console.log("");

    // ========== 6. 二次销售（版税演示） ==========
    console.log("🔄 步骤 6: User1 转售NFT（触发版税）");
    console.log("-".repeat(50));
    
    const newPrice = hre.ethers.parseEther("0.15");
    const relistTx = await nft.connect(user1).listNFT(0, newPrice);
    await relistTx.wait();
    
    console.log("✅ NFT #0 重新挂单");
    console.log("   - 新价格:", hre.ethers.formatEther(newPrice), "ETH");
    console.log("   - 版税将支付给原创作者:", creator);
    console.log("");

    // User2 购买
    const buyTx2 = await nft.connect(user2).buyNFT(0, { value: newPrice });
    await buyTx2.wait();
    
    console.log("✅ User2 购买成功");
    console.log("   - 平台手续费: 2.5% =", hre.ethers.formatEther(newPrice * 250n / 10000n), "ETH");
    console.log("   - 创作者版税: 10% =", hre.ethers.formatEther(newPrice * 1000n / 10000n), "ETH");
    console.log("   - 卖家收入: 87.5% =", hre.ethers.formatEther(newPrice * 8750n / 10000n), "ETH");
    console.log("");

    // ========== 7. 批量铸造 ==========
    console.log("🎨 步骤 7: 批量铸造NFT");
    console.log("-".repeat(50));
    
    const batchURIs = [
      "ipfs://QmBatch1/metadata.json",
      "ipfs://QmBatch2/metadata.json",
      "ipfs://QmBatch3/metadata.json"
    ];
    
    const batchTx = await nft.connect(owner).batchMint(owner.address, batchURIs, 500);
    await batchTx.wait();
    
    console.log("✅ 批量铸造成功");
    console.log("   - 数量:", batchURIs.length);
    console.log("   - 版税: 5%");
    console.log("");

    // ========== 8. 查询用户拥有的NFT ==========
    console.log("📊 步骤 8: 查询各用户拥有的NFT");
    console.log("-".repeat(50));
    
    const ownerTokens = await nft.tokensOfOwner(owner.address);
    const user1Tokens = await nft.tokensOfOwner(user1.address);
    const user2Tokens = await nft.tokensOfOwner(user2.address);
    
    console.log("   Owner拥有:", ownerTokens.length, "个 -", ownerTokens.toString());
    console.log("   User1拥有:", user1Tokens.length, "个 -", user1Tokens.toString());
    console.log("   User2拥有:", user2Tokens.length, "个 -", user2Tokens.toString());
    console.log("");

    // ========== 9. 合约统计 ==========
    console.log("📈 步骤 9: 合约统计信息");
    console.log("-".repeat(50));
    
    const totalSupply = await nft.totalSupply();
    const platformFee = await nft.platformFeePercent();
    const feeRecipient = await nft.feeRecipient();
    const contractBalance = await hre.ethers.provider.getBalance(contractAddress);
    
    console.log("   总供应量:", totalSupply.toString());
    console.log("   平台手续费:", Number(platformFee) / 100, "%");
    console.log("   手续费接收地址:", feeRecipient);
    console.log("   合约余额:", hre.ethers.formatEther(contractBalance), "ETH");
    console.log("");

    console.log("🎉 所有操作完成！");
    console.log("=".repeat(50));

  } catch (error) {
    console.error("❌ 错误:", error.message);
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

